<template>
  <div class="home">
    <div ref="echartsRef" :style="{ width: nowWidth }" class="echart-dom"></div>
  </div>
</template>
<script setup>
import * as echarts from 'echarts'
import { onMounted, ref } from 'vue'
import { hasSuffix, removePercentSymbol, getNumberFromString } from '@/utils/public'
import * as props from './modules/multipleData'
const nowWidth = ref('530px')
// 存储legend数据
const legendData = ref([])
// echarts图表显示数据
const seriesData = ref({})
// 提取出来的原始数据
const originData = ref({})
// 根据数据类型
const titleTypeList = ref([])
// 存储series
const seriesArr = ref([])
const isArea = ref(false)
const echartsRef = ref(null)
onMounted(() => {
  getData()
})
const getData = () => {
  isArea.value = props.title.indexOf('区域') !== -1
  // 查看title中是否有区域，如果有则需要将数据进行拆分
  computedData(props.title, props.titleType, '区域', isArea.value)
  // 新增对应的筛选数组
  filterData()
  // 筛选数据，转换单位
  computedSeriesData()
  // 初始化出series数据
  initData()
  // console.log('seriesArr.value', seriesArr.value)
  initEcharts()
}
// 筛选数据，转换单位
const computedSeriesData = () => {
  let copyData = JSON.parse(JSON.stringify(props.body))
  let readyData = copyData.map((item) => {
    if (item.index) {
      delete item.index
    }
    return item
  })
  readyData.forEach((item) => {
    if (isArea.value) {
      seriesData.value.key2.push(`${item.key1}-${item.key2}`)
      originData.value.key2.push(`${item.key1}-${item.key2}`)
      delete item.key1
      delete item.key2
    } else {
      seriesData.value.key1.push(item.key1)
      originData.value.key1.push(item.key1)
      delete item.key1
    }
    Object.keys(item).forEach((key) => {
      if (seriesData.value[key]) {
        item[key] = item[key] == 'null' ? 0 : item[key]
        originData.value[key].push(item[key])
        if (item[key] != 0 && hasSuffix(item[key]) !== 0) {
          item[key] =
            hasSuffix(item[key]) === 1
              ? removePercentSymbol(item[key])
              : getNumberFromString(item[key])
        }
        seriesData.value[key].push(item[key])
      }
    })
  })
}
// 筛选数据legend
const computedData = (baseData = [], titleType = [], title, isArea) => {
  let backData = []
  let titleData = []
  if (isArea) {
    backData = baseData.slice(baseData.indexOf(title) + 1)
    titleData = titleType.slice(baseData.indexOf(title) + 1)
  } else {
    backData = baseData.slice(1)
    titleData = titleType.slice(1)
  }
  titleTypeList.value = titleData
  legendData.value = backData
}
// 新增对应的筛选数组
const filterData = () => {
  let lastIndex = 0
  legendData.value.forEach((item, index) => {
    lastIndex = isArea.value ? index + 2 : index + 1
    seriesData.value['key' + lastIndex] = []
  })
  seriesData.value['key' + (lastIndex + 1)] = []
  originData.value = JSON.parse(JSON.stringify(seriesData.value))
}
// 初始化出series数据
const initData = () => {
  seriesArr.value = []

  titleTypeList.value.forEach((item, index) => {
    let itemData = {
      name: legendData.value[index],
      type: item == 2 ? 'bar' : 'line',
      yAxisIndex: item == 2 ? 0 : 1,
      label: {
        show: true,
        position: item == 2 ? [10, -10] : 'inside',
        formatter:
          item == 2
            ? function (params) {
                return originData.value['key' + (isArea.value ? index + 3 : index + 2)][
                  params.dataIndex
                ]
              }
            : '{c}%'
      },
      data: seriesData.value['key' + (isArea.value ? index + 3 : index + 2)]
    }
    if (item === 2) {
      itemData.barWidth = 12
    }
    seriesArr.value.push(itemData)
  })
}
// 初始化echarts
const initEcharts = () => {
  const myEcharts = echarts.init(echartsRef.value)
  const axisData = isArea.value ? seriesData.value.key2 : seriesData.value.key1
  const option = {
    tooltip: {
      trigger: 'axis',
      backgroundColor: 'rgba(255,255,255,0.9)',
      formatter: function (params) {
        let str = params[0].name + '<br/>'
        const listData = []
        params.forEach((item, index) => {
          for (const key in originData.value) {
            listData.push(originData.value[key][item.dataIndex])
          }
          const newList = listData.filter((item, i) => i !== 0)
          str += item.marker + item.seriesName + '：' + newList[index] + '<br/>'
        })
        return str
      }
    },
    grid: {
      left: -40,
      right: '8%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: axisData
    },
    yAxis: [
      {
        show: false
      },
      {
        show: false
      }
    ],
    series: seriesArr.value,
    dataZoom: [
      {
        start: 0, // 默认为0
        end: Math.floor(100 / axisData.length) * 6, //  默认为100（重点）
        type: 'slider',
        show: false,
        borderColor: 'transparent',
        borderCap: 'round',
        xAxisIndex: [0],
        height: 2,
        left: 20,
        right: 20,
        bottom: 40,
        fillerColor: '#2994FF',
        handleSize: '100%',
        handleStyle: {
          color: '#2994FF',
          borderWidth: 0
        },
        backgroundColor: '#DFE3E8',
        showDataShadow: false,
        showDetail: false,
        filterMode: 'filter',
        brushSelect: false
      },
      {
        type: 'inside',
        zoomOnMouseWheel: false,
        moveOnMouseMove: true,
        moveOnMouseWheel: true
      }
    ]
  }
  myEcharts.setOption(option)
  window.addEventListener('resize', function () {
    myEcharts.resize()
  })
}
</script>
<style lang="scss" scoped>
.home {
  height: 480px;
  display: flex;
  justify-content: center;
  align-items: center;
}
.echart-dom {
  width: 530px;
  height: 300px;
}
</style>
